<template>
  <div class="profile-page">
    <div class="profile-header">
      <h2>个人中心</h2>
    </div>

    <el-tabs v-model="activeTab" class="profile-tabs">
      <!-- 个人信息 -->
      <el-tab-pane label="个人信息" name="info">
        <div class="profile-section">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar :size="120" :src="getAvatarUrl(userInfo.avatar)" :icon="UserFilled" class="user-avatar" />
              <el-button type="primary" size="small" class="change-avatar-btn" @click="handleChangeAvatar">
                更换头像
              </el-button>
            </div>
          </div>

          <el-form ref="profileForm" :model="profileData" :rules="profileRules" label-width="100px"
            class="profile-form">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileData.username" disabled />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileData.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileData.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveProfile" :loading="saveLoading">
                保存信息
              </el-button>
              <el-button @click="handleResetProfile">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 修改密码 -->
      <el-tab-pane label="修改密码" name="password">
        <div class="password-section">
          <el-form ref="passwordForm" :model="passwordData" :rules="passwordRules" label-width="120px"
            class="password-form">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input v-model="passwordData.oldPassword" type="password" placeholder="请输入当前密码" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordData.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordData.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                修改密码
              </el-button>
              <el-button @click="handleResetPassword">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="logs">
        <div class="logs-section">
          <el-table :data="userLogs" v-loading="logsLoading" border stripe>
            <el-table-column prop="action" label="操作类型" width="200">
              <template #default="{ row }">
                <el-tag type="warning" size="small">
                  {{ getActionText(row.action) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作模块" width="150">
              <template #default="{ row }">
                <el-tag type="primary" size="small">
                  {{ getModuleText(row.resource) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ipAddress" label="IP地址" width="200" />
            <el-table-column prop="userAgent" label="设备信息" min-width="200" show-overflow-tooltip />
            <el-table-column prop="createdAt" label="操作时间" width="200">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination v-model:current-page="logsPagination.page" v-model:page-size="logsPagination.pageSize"
              :page-sizes="[10, 20, 50]" :total="logsPagination.total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleLogsPageSizeChange" @current-change="handleLogsPageChange" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 头像上传对话框 -->
    <el-dialog title="更换头像" v-model="avatarDialogVisible" width="400px">
      <div class="avatar-upload">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar">
          <img v-if="previewAvatar?.url" :src="previewAvatar.url" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="upload-tip">
          <p>只能上传jpg/png文件，且不超过2MB</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatar" :loading="avatarLoading">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'UserProfile'
})

import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { emailRules,phoneRules } from '@/utils/validationRules'
const userStore = useUserStore()

// 响应式数据
const activeTab = ref('info')
const profileForm = ref()
const passwordForm = ref()
const saveLoading = ref(false)
const passwordLoading = ref(false)
const logsLoading = ref(false)
const avatarLoading = ref(false)
const avatarDialogVisible = ref(false)
const previewAvatar = ref('')

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 个人信息表单
const profileData = reactive({
  username: '',
  email: '',
  phone: ''
})

// 密码修改表单
const passwordData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户日志
const userLogs = ref([])
const logsPagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 验证规则
const profileRules = {
  email: emailRules,
  phone: phoneRules
}
const getModuleText = (module) => {
  const moduleMap = {
    'Users': '用户管理',
    'Roles': '角色管理',
    'Menus': '菜单管理',
    'System': '系统设置',
    'auth': '认证',
    'OperationLogs': '日志管理',
    'Files': '文件管理',
    'Articles': '文章管理',
    'ArticleCategories': '文章分类管理',
    'SystemConfigs': '系统配置',
    'system_configs':'系统设置',
    'Auth':'认证'
  };
  return moduleMap[module] || module;
};
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordData.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 模拟用户日志数据 - 已移除，现在从API获取

// 方法
const loadUserProfile = async () => {
  try {
    // 从API获取用户信息并填充到表单
    const user = await userStore.getUserProfile();
    console.log('用户信息:', user);

    Object.assign(profileData, {
      username: user.username || '',
      email: user.email || '',
      phone: user.phone || ''
    })

    // 更新store中的用户信息
    userStore.setUserInfo(user)
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

const loadUserLogs = async () => {
  logsLoading.value = true
  try {
    const result = await userStore.getUserLogs(logsPagination.page, logsPagination.pageSize)
    userLogs.value = result.items || []
    logsPagination.total = result.totalCount || 0
  } catch (error) {
    console.error('加载操作日志失败:', error)
    ElMessage.error('加载操作日志失败')
  } finally {
    logsLoading.value = false
  }
}

const handleSaveProfile = async () => {
  if (!profileForm.value) return

  try {
    await profileForm.value.validate()
    saveLoading.value = true

    // 调用真实API更新个人信息 - 只发送可修改的字段
    await userStore.updateProfile({
      email: profileData.email,
      phone: profileData.phone,
      // avatar字段通过专门的头像上传功能处理
    })

    // 重新加载用户信息
    await loadUserProfile()

    ElMessage.success('个人信息保存成功')
  } catch (error) {
    console.error('保存个人信息失败:', error)
    if (error.message && error.message !== 'false') {
      ElMessage.error('保存失败: ' + error.message)
    } else {
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    saveLoading.value = false
  }
}

const handleResetProfile = () => {
  loadUserProfile()
}

const handleChangePassword = async () => {
  if (!passwordForm.value) return

  try {
    await passwordForm.value.validate()
    passwordLoading.value = true

    // 调用真实API修改密码
    await userStore.changePassword({
      oldPassword: passwordData.oldPassword,
      newPassword: passwordData.newPassword,
      confirmPassword: passwordData.confirmPassword
    })

    ElMessage.success('密码修改成功')
    handleResetPassword()
  } catch (error) {
    console.error('密码修改失败:', error)
    if (error.message && error.message !== 'false') {
      ElMessage.error('密码修改失败: ' + error.message)
    } else {
      ElMessage.error('密码修改失败，请重试')
    }
  } finally {
    passwordLoading.value = false
  }
}

const handleResetPassword = () => {
  Object.assign(passwordData, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  if (passwordForm.value) {
    passwordForm.value.clearValidate()
  }
}

const handleChangeAvatar = () => {
  // 初始化预览为当前头像
  if (userInfo.value.avatar) {
    previewAvatar.value = {
      file: null,
      url: getAvatarUrl(userInfo.value.avatar)
    }
  } else {
    previewAvatar.value = null
  }
  avatarDialogVisible.value = true
}

const getAvatarUrl = (avatar) => {
  if (!avatar) return ''

  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar
  }

  // 如果是相对路径，加上后端基础URL
  const baseUrl = 'http://admin-lusiyi.ijelly.cn'
  if (avatar.startsWith('/')) {
    return baseUrl + avatar
  } else {
    return baseUrl + '/' + avatar
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadAvatar = (options) => {
  const file = options.file
  // 保存文件对象和预览URL
  previewAvatar.value = {
    file: file,
    url: URL.createObjectURL(file)
  }
  return Promise.resolve()
}

const confirmAvatar = async () => {
  if (!previewAvatar.value?.file) {
    ElMessage.error('请先选择头像')
    return
  }

  try {
    avatarLoading.value = true

    // 构建FormData
    const formData = new FormData()
    formData.append('file', previewAvatar.value.file)

    // 调用真实API上传头像
    await userStore.uploadAvatar(formData)

    // 重新加载用户信息以获取新头像URL
    await loadUserProfile()

    ElMessage.success('头像更换成功')
    avatarDialogVisible.value = false
  } catch (error) {
    console.error('头像上传失败:', error)
    if (error.message && error.message !== 'false') {
      ElMessage.error('头像上传失败: ' + error.message)
    } else {
      ElMessage.error('头像上传失败')
    }
  } finally {
    avatarLoading.value = false
  }
}

const getActionText = (action) => {
  const actionMap = {
    'operationlogs.search': '获取日志',
    'operationlogs.create': '日志创建',
    'operationlogs.update': '日志更新',
    'operationlogs.exportcsv': '日志导出',
    'users.getusers': '获取用户列表',
    'users.createuser': '创建用户',
    'users.updateuser': '更新用户',
    'users.deleteuser': '删除用户',
    'users.updateprofile ': '更新个人信息',
    'users.changepassword': '修改密码',
    'auth.login': '用户登录',
    'auth.logout': '用户登出',
    'auth.register': '用户注册',
    'auth.refreshtoken': '令牌刷新',
    'roles.getroles': '获取角色列表',
    'roles.createrole': '创建角色',
    'roles.updaterole': '更新角色',
    'roles.deleterole': '删除角色',
    'menus.getmenus': '获取菜单列表',
    'menus.createmenu': '创建菜单',
    'menus.updatemenu': '更新菜单',
    'menus.deletemenu': '删除菜单',
    'menus.getmenutree': '获取菜单树',
    'settings.getsettings': '获取系统设置',
    'systemconfigs.getall': '获取系统配置',
    'SystemConfig.BatchUpdate': '系统配置批量更新',
    'systemconfigs.batchupdate': '系统配置批量更新',
    'users.resetpasswordself': '用户重置密码',
    'auth.getprofile': '获取用户信息',
    'files.getmyfiles': '获取文件',
    'files.upload': '上传文件',
    'files.download': '下载文件',
    'files.deletefile': '删除文件',
    'files.search': '文件搜索',
    'exception': '出错了',
    'articles.getarticles': '获取文章列表',
    'articlecategories.update': '更新类名',
    'articlecategories.create': '创建类名',
    'articlecategories.delete': '删除类名',
    'articlecategories.getall': '获取文章类别',
    'articles.updatearticle': '更新文章',
    'articles.createarticle': '创建文章',
    'articles.deletearticle': '删除文章',
    'articles.getarticle': '查看文章',

  }
  return actionMap[action] || action
}

const getActionTagType = (action) => {
  const actionMap = {
    'User.Login': 'success',
    'User.Logout': 'info',
    'User.Update': 'warning',
    'User.ChangePassword': 'danger',
    'User.UploadAvatar': 'primary',
    'SystemConfig.Update': 'warning',
    'SystemConfig.BatchUpdate': 'warning'
  }
  return actionMap[action] || 'info'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const handleLogsPageSizeChange = (val) => {
  logsPagination.pageSize = val
  logsPagination.page = 1
  loadUserLogs()
}

const handleLogsPageChange = (val) => {
  logsPagination.page = val
  loadUserLogs()
}

// 生命周期
onMounted(() => {
  loadUserProfile()
  loadUserLogs()
})
</script>

<style scoped>
.profile-page {
  padding: 20px;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-header h2 {
  margin: 0;
  color: #333;
}

.profile-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.profile-section {
  display: flex;
  gap: 40px;
  max-width: 1000px;
}

.avatar-section {
  flex-shrink: 0;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.user-avatar {
  border: 3px solid #f0f0f0;
}

.change-avatar-btn {
  width: 100px;
}

.profile-form {
  flex: 1;
  max-width: 600px;
}

.password-section,
.logs-section {
  max-width: 100%;
}

.password-form {
  max-width: 500px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  display: inline-block;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  object-fit: cover;
  display: block;
}

.upload-tip {
  margin-top: 10px;
}

.upload-tip p {
  margin: 0;
  color: #999;
  font-size: 12px;
}

:deep(.el-tabs__header) {
  margin-bottom: 30px;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 30px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
}
</style>
